﻿using System.Data;
using System.IO;
using System.Xml.Linq;
using System.Xml.Serialization;

namespace DNT.Extensions
{
    public static class XmlExtensions
    {

        /// <summary>
        /// Converts entire DataTabel To XDocument
        /// Example:
        /// DataTable dtCert = new DataTable();
        /// dtCert.ToXml("Certs");
        /// </summary>
        /// <param name="dt">Data Table</param>
        /// <param name="rootName">Root Name</param>
        /// <returns>XDocument</returns>
        public static XDocument DataTableToXml(this DataTable dt, string rootName)
        {
            var xdoc = new XDocument
                           {
                               Declaration = new XDeclaration("1.0", "utf-8", "")
                           };
            xdoc.Add(new XElement(rootName));
            foreach (DataRow row in dt.Rows)
            {
                var element = new XElement(dt.TableName);
                foreach (DataColumn col in dt.Columns)
                {
                    element.Add(new XElement(col.ColumnName, row[col].ToString().Trim(' ')));
                }
                if (xdoc.Root != null) xdoc.Root.Add(element);
            }
            return xdoc;
        }

        /// <summary>
        /// Serializes an object to XML
        /// Example:
        /// var f = new Foo
        ///         {
        ///             bar = "hi",
        ///             baz = new List<string> {"quick", "brown", "fox"}
        ///         };
        /// Console.WriteLine(f.ToXML());
        /// </summary>
        /// <typeparam name="T">Type of class</typeparam>
        /// <param name="o">object</param>
        /// <returns>Xml as string</returns>
        public static string ToXML<T>(this T o)
            where T : new()
        {
            string retVal;
            using (var ms = new MemoryStream())
            {
                var xs = new XmlSerializer(typeof (T));
                xs.Serialize(ms, o);
                ms.Flush();
                ms.Position = 0;
                var sr = new StreamReader(ms);
                retVal = sr.ReadToEnd();
            }
            return retVal;
        }

       

    }
}
